package com.itheima.sh;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @Author 张伟奇
 * @Date 2021/5/17 17:32
 * @Version 1.0
 **/
@WebServlet("/download")
public class MyServlet02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //获取前端请求，拿到需要下在的文件名称
        String filename = req.getParameter("filename");
        //设置响应下载文件的专用头
        // 解决方案,使用浏览器的解码方式进行对文件名称编码
        String downloadName = URLEncoder.encode(filename,"utf-8");
        resp.setHeader("content-disposition","attachment;filename="+downloadName);
        //设置文件的类型
        ServletContext servletContext = getServletContext();
        String mimeType = servletContext.getMimeType(filename);


        resp.setContentType(mimeType);
        //获取被下载的文件路径
        String realPath = servletContext.getRealPath("/download/" + filename);
        //使用流将服务器中的文件以流的形式写回给浏览器
        FileInputStream fileInputStream = new FileInputStream(realPath);
        ServletOutputStream outputStream = resp.getOutputStream();
        byte[] b=new byte[1024];
        int len=0;
        while ((len=fileInputStream.read(b))!=-1){
            outputStream.write(b,0,len);
        }
        fileInputStream.close();
        outputStream.close();
    }
}
